package com.pfzy.lib.net.convert;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Converter;

/**
 * 自定义请求RequestBody
 */
public class JsonRequestBodyConverter implements Converter<Object, RequestBody> {
    private final String TAG = "JsonRequestBodyConverter";
    private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
    private final Gson gson;
    private final TypeAdapter adapter;
    private boolean isEncrypt;

    /**
     * 构造器
     */
    JsonRequestBodyConverter(Gson gson, TypeAdapter adapter,boolean isEncrypt) {
        this.gson = gson;
        this.adapter = adapter;
        this.isEncrypt = isEncrypt;
        Log.d(TAG, "IRequestBodyConverter初始化");
    }

    @Override
    public RequestBody convert(Object value) throws IOException {
        // 将传入的实体类先转成json，再进行加密
        String json = gson.toJson(value);
        if(isEncrypt) {
            Log.d(TAG, "#加密前#"+ json);
            try {
//                json = MyAES.aesEncryptT(json);
            } catch (Exception ex) {
                Log.d(TAG, "#加密出错#" + ex.getMessage());
                json = "";
            }
            Log.d(TAG, "#加密后#" + json);
        }
        return RequestBody.create(MEDIA_TYPE, json);
    }
}
